package org.dromara.system.controller.system;

import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.bo.*;
import org.dromara.system.domain.vo.SummaryTradingPointsVo;
import org.dromara.system.domain.vo.SysUserMachineVo;
import org.dromara.system.enums.MachineConstant;
import org.dromara.system.listener.SysUserMachineListener;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysUserMachineService;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 机具信息
 *
 * @author Lion Li
 * @date 2025-07-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/userMachine")
public class SysUserMachineController extends BaseController {

    private final ISysUserMachineService sysUserMachineService;
    private final SysUserMapper sysUserMapper;

    /**
     * 查询机具信息列表
     */
//    @SaCheckPermission("system:userMachine:list")
    @GetMapping("/list")
    public TableDataInfo<SysUserMachineVo> list(SysUserMachineBo bo, PageQuery pageQuery) {
        return sysUserMachineService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出机具信息列表
     */
//    @SaCheckPermission("system:userMachine:export")
    @Log(title = "机具信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SysUserMachineBo bo, HttpServletResponse response) {
        List<SysUserMachineVo> list = sysUserMachineService.queryList(bo);
        ExcelUtil.exportExcel(list, "机具信息", SysUserMachineVo.class, response);
    }

    /**
     * 获取机具信息详细信息
     *
     * @param id 主键
     */
//    @SaCheckPermission("system:userMachine:query")
    @GetMapping("/{id}")
    public R<SysUserMachineVo> getInfo(@NotNull(message = "主键不能为空")
                                       @PathVariable Long id) {
        return R.ok(sysUserMachineService.queryById(id));
    }

    /**
     * 新增机具信息
     */
//    @SaCheckPermission("system:userMachine:add")
    @Log(title = "机具信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysUserMachineBo bo) {
        return toAjax(sysUserMachineService.insertByBo(bo));
    }

    /**
     * 修改机具信息
     */
//    @SaCheckPermission("system:userMachine:edit")
    @Log(title = "机具信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysUserMachineBo bo) {
        return toAjax(sysUserMachineService.updateByBo(bo));
    }

    /**
     * 删除机具信息
     *
     * @param ids 主键串
     */
//    @SaCheckPermission("system:userMachine:remove")
    @Log(title = "机具信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(sysUserMachineService.deleteWithValidByIds(List.of(ids), true));
    }


    /**
     * 导入表格
     */
//    @SaCheckPermission("system:userMachine:importMachine")
    @PostMapping(value = "/importMachine", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importMachine(@RequestPart("file") MultipartFile file
        , @RequestParam(value = "machinePolicyId", required = true) Long machinePolicyId
        , @RequestParam(value = "brandId", required = true) Long brandId
        , @RequestParam(value = "lineId", required = true) Long lineId
        , @RequestParam(value = "machineModelId", required = true) Long machineModelId
    ) throws Exception {
        // 处理解析结果
        MachinePutBo machinePutBo = MachinePutBo.builder()
            .machinePolicyId(machinePolicyId)
            .isSupportUpdate(Boolean.TRUE)
            .brandId(brandId)
            .lineId(lineId)
            .machineModelId(machineModelId)
            .userId(LoginHelper.getUserId())
            .build();
        ExcelResult<SysUserMachineVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), SysUserMachineVo.class, new SysUserMachineListener(machinePutBo));
        return R.ok(excelResult.getAnalysis());
    }

    //    @SaCheckPermission("system:userMachine:importMachine")
    @PostMapping(value = "/saveMachine", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @RepeatSubmit()
    public R<Void> saveMachine(@RequestParam(value = "sn", required = true) String sn
        , @RequestParam(value = "machinePolicyId", required = true) Long machinePolicyId
        , @RequestParam(value = "brandId", required = true) Long brandId
        , @RequestParam(value = "lineId", required = true) Long lineId
        , @RequestParam(value = "machineModelId", required = true) Long machineModelId
    ) throws Exception {
        SysUser sysUser = sysUserMapper.selectById(LoginHelper.getUserId());
        BusinessException.isTrue(ObjectUtil.notEqual(sysUser.getPId(), MachineConstant.ADMIN), "需一级代理商入库机器！");
        // 处理解析结果
        MachinePutBo machinePutBo = MachinePutBo.builder()
            .machinePolicyId(machinePolicyId)
            .isSupportUpdate(Boolean.TRUE)
            .brandId(brandId)
            .lineId(lineId)
            .machineModelId(machineModelId)
            .userId(LoginHelper.getUserId())
            .build();
        return toAjax(sysUserMachineService.saveMachine(machinePutBo, sn));
    }

    @Log(title = "商户绑定机器", businessType = BusinessType.OTHER)
    @PostMapping("/bindMachine")
    @RepeatSubmit(interval = 8, timeUnit = TimeUnit.SECONDS, message = "点太快啦，稍后再试！")
    public R<Void> bindMachine(@RequestBody BindMachineBo bindMachineBo) {
        return toAjax(sysUserMachineService.bindMachine(bindMachineBo));
    }


    //    @SaCheckPermission("system:userMachineAssociation:unBindMachine")
    @Log(title = "商户解绑机器", businessType = BusinessType.OTHER)
    @PostMapping("/unBindMachine")
    @RepeatSubmit(interval = 8, timeUnit = TimeUnit.SECONDS, message = "点太快啦，稍后再试！")
    public R<Void> unBindMachine(@RequestBody BindMachineBo bindMachineBo) {
        return toAjax(sysUserMachineService.unBindMachine(bindMachineBo));
    }


    @Log(title = "后台解绑机器", businessType = BusinessType.OTHER)
    @PostMapping("/backendUnBindMachine")
    @RepeatSubmit(interval = 8, timeUnit = TimeUnit.SECONDS, message = "点太快啦，稍后再试！")
    public R<Void> backendUnBindMachine(@RequestBody @Validated BackendUnBindMachineBo bo) {
        return toAjax(sysUserMachineService.backendUnBindMachine(bo));
    }

    //    @SaCheckPermission("system:userMachineAssociation:queryBindMachine")
    @Log(title = "查询商户绑定的机器列表", businessType = BusinessType.OTHER)
    @GetMapping("/queryBindMachine")
    public TableDataInfo<SysUserMachineVo> queryBindMachine(QueryBindMachineBo queryBindMachineBo, PageQuery pageQuery) {
        return sysUserMachineService.queryBindMachine(queryBindMachineBo, pageQuery);
    }


    @PostMapping("/summaryTradingPoints")
    public R<SummaryTradingPointsVo> summaryTradingPoints(@RequestBody SummaryTradingPointsBo bo) {
        return R.ok(sysUserMachineService.summaryTradingPoints(bo));
    }


}
